package com.bds.tjj.action;

import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bds.tjj.model.common.Result;
import com.bds.tjj.utils.Const;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bds.tjj.service.ExportService;

@Controller
@RequestMapping("/service/data/export")
public class ExportAction extends BaseAction {
    private static Logger LOGGER = Logger.getLogger(ExportAction.class);

    @Autowired
    private ExportService exportService;

    @RequestMapping(value = "/excel/{type}/{prop}/{time}")
    public Result exportExcel(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable String type,
                              @PathVariable String prop, @PathVariable String time) throws Exception {
        Result ret = new Result();

        try {
            int startTime, endTime;
            try {
                if (type.equals("y")) {
                    startTime = Integer.parseInt(time.split("-")[0].substring(0, 4));
                    endTime = Integer.parseInt(time.split("-")[1].substring(0, 4));
                } else {
                    startTime = Integer.parseInt(time.split("-")[0].substring(0, 6));
                    endTime = Integer.parseInt(time.split("-")[1].substring(0, 6));
                }
            } catch (Exception e) {
                ret.setResult(Const.FAIL, "参数异常");
                LOGGER.warn("get_year_trend 参数异常：", e);
                return ret;
            }

            String fileName = exportService.getFileName(prop) + "_" + startTime + "-" + endTime;
            HSSFWorkbook wb = exportService.exportExcel(type, prop, startTime, endTime);
            if (wb != null) {
                DateFormat FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
                fileName = fileName + "_" + FORMAT.format(new Date()) + ".xls";
                response.setContentType("application/vnd.ms-excel");
                //filename用双引号包裹，否则谷歌、360等浏览器可能报错
                response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                OutputStream out = response.getOutputStream();
                wb.write(out);
                out.flush();
                out.close();
            }

        } catch (Exception e) {
            LOGGER.error("", e);

        }

        return ret;

    }

}
